package com.homedo.microservice.wechat.personal.secretary.service;

import com.homedo.common.bean.vo.context.UserContext;
import com.homedo.microservice.wechat.personal.secretary.cache.BizCache;
import com.homedo.microservice.wechat.personal.secretary.cache.BizCodeCorrespondingRelationCache;
import com.homedo.microservice.wechat.personal.secretary.cache.PersonalBotCache;
import com.homedo.microservice.wechat.personal.secretary.entity.Biz;
import com.homedo.microservice.wechat.personal.secretary.entity.PersonalBot;
import com.homedo.microservice.wechat.personal.secretary.entity.PersonalBotBiz;
import io.github.biezhi.wechat.api.constant.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class PersonalBotService {
    private static final Logger _LOGGER = LoggerFactory.getLogger(PersonalBotService.class);

    public PersonalBot getPersonalBot(String sysLoginAccount, UserContext userContext) {
        return this.getPersonalBot(sysLoginAccount);
    }

    public List<Biz> getBizByAccount(String sysLoginAccount, UserContext userContext) {
        //TODO 这里应该从数据库中拉取对应用户的BIZ

        List<Biz> bizs = new ArrayList<>();

        BizCache.BIZ_CACHE.values().forEach(e -> {
            String bizClazzName = BizCodeCorrespondingRelationCache.CACHE.get(e.getCode());
            try {
                Class bizClazz = Class.forName(bizClazzName);
                Biz biz = (Biz) bizClazz.newInstance();

                bizs.add(biz);
            } catch (Exception ex) {
                _LOGGER.error("[初始化业务类错误:{},{}]", e.getCode(), bizClazzName, ex);
            }

        });
        return bizs;
    }

    public boolean checkBizExist(String bizCode, UserContext userContext) {
        Biz biz = BizCache.BIZ_CACHE.get(bizCode);
        if (biz == null) {
            return false;
        }
        return true;
    }

    private PersonalBot getPersonalBot(String sysLoginAccount) {
        PersonalBot personalBot = PersonalBotCache.PERSONALBOT_CACHE.get(sysLoginAccount);
        if (personalBot == null) {
            PersonalBot newPersonalBot = this.newPersonalBot(sysLoginAccount);
            PersonalBot oldPersonalBot = PersonalBotCache.PERSONALBOT_CACHE.putIfAbsent(sysLoginAccount, newPersonalBot);
            if (oldPersonalBot == null) {
                newPersonalBot.start();//新的需要启动
                personalBot = newPersonalBot;
            } else {
                personalBot = oldPersonalBot;
            }
        }
        return personalBot;
    }

    private PersonalBot newPersonalBot(String sysLoginAccount) {
        PersonalBot personalBot = new PersonalBot(Config.me().autoLogin(false).showTerminal(false).filePrefix(sysLoginAccount + "_").sysLoginAccount(sysLoginAccount));
        personalBot.setBotBiz(new PersonalBotBiz(personalBot, this));

        return personalBot;
    }

}
